#include <stdio.h>
#include <stdlib.h>
#include <Python.h>
#include <unistd.h>
#include <string.h>



#define WEGET_CMD "libcamera-jpeg -o /tmp/SearchFace.jpg"
#define SEARCHFACE_FILE  "/tmp/SearchFace.jpg"


void face_initialize(void)
 {
    Py_Initialize();
    // 将当前路径添加到sys.path中
    PyObject *sys = PyImport_ImportModule("sys");
    if(sys == NULL)
    {
        Py_DECREF(sys);
    }
    PyObject *path = PyObject_GetAttrString(sys, "path");
    if(path == NULL)
    {
        Py_DECREF(path);
    }
    PyList_Append(path, PyUnicode_FromString("."));
 }

char* get_result(char* result)
{
    system(WEGET_CMD);
    if(access(SEARCHFACE_FILE,F_OK) != 0)
    {
        return result;
    }
    printf("拍照成功\n");
    PyObject *pModule = PyImport_ImportModule("face");//导入face.py模块
    if (!pModule)
    {
        PyErr_Print();
        printf("Error: failed to load face.py\n");
        goto FAILED_MODULE;
    }
    printf("1\n");
    PyObject *pFunc = PyObject_GetAttrString(pModule, "search_Face");//获取search_Face函数对象
    if (!pFunc)
    {
        PyErr_Print();
        printf("Error: failed to load search_Face\n");
        goto FAILED_FUNC;
    }
    printf("2\n");
    PyObject *pValue = PyObject_CallObject(pFunc, NULL);//调用alibabacloud_face函数并获取返回值
    if (!pValue)
    {
        PyErr_Print();
        printf("Error: function call failed\n");
        goto FAILED_VALUE;
    }
    printf("3\n");
    char *temp = NULL;
    if  (!PyArg_Parse(pValue, "s", &temp))//解析获取alibabacloud_face函数的返回值，转行为C语言格式
    {
        PyErr_Print();
        printf("Error: parse failed");
        goto FAILED_RESULT;
    }
    printf("4\n");
    printf("%s|temp = %s\n",__func__,temp);
    strcpy(result,temp);
FAILED_RESULT:
    Py_DECREF(pValue);
FAILED_VALUE:
    Py_DECREF(pFunc);
FAILED_FUNC:
    Py_DECREF(pModule);
FAILED_MODULE:
    return result;
}

void get_face_source(char *result)
{
    face_initialize();
    get_result(result);
}

// int main()
// {
//     face_initialize();
//     char result[128] = {0};
//     get_result(result);
//     printf("main.c:%s\n",result);
//     return 0;
// }